import { HttpParams } from '@angular/common/http';
import { ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { ModalHelper, _HttpClient, SettingsService } from '@delon/theme';
import { ModalHelperOptions } from '@delon/theme/src/services/modal/modal.helper';
import { NzImage, NzImageService } from 'ng-zorro-antd/image';
import { NzMessageService } from 'ng-zorro-antd/message';

import { BusinessRefundProcessComponent } from '../refund-process/refund-process.component';

@Component({
  selector: 'app-business-refund',
  templateUrl: './refund.component.html'
})
export class BusinessRefundComponent implements OnInit {
  url = `api/refunds`;
  isAdmin = false;
  isShow = false;
  company_id = 0;
  q: {
    externalOrderType: number;
    warehouseId: number;
    skuType: string;
    skuTypeValue: string;
    shopId: number;
    companyId: number;
  } = {
    skuType: 'skuId',
    skuTypeValue: '',
    shopId: 0,
    companyId: 0,
    externalOrderType: 0,
    warehouseId: 3
  };
  shops = [];
  shopMap = {};
  skuTypeOptions = [
    { index: 'skuId', text: 'Fordeal SKU', checked: true },
    { index: 'skuNo', text: '商家SKU' },
    { index: 'itemId', text: '商品ID' },
    { index: 'itemNo', text: '商品货号' }
  ];
  externalOrderTypeOptions = [
    { index: 0, text: '全部' },
    { index: 1, text: '发货单' },
    { index: 2, text: '客退返仓' },
    { index: 3, text: '仓库巡检' },
    { index: 4, text: '拒签返仓' },
    { index: 5, text: '货件' }
  ];
  listOfData: any;
  loading = true;
  total = 0;
  ps = 50;
  pi = 1;
  desc: any[] = [];

  constructor(
    private http: _HttpClient,
    private modal: ModalHelper,
    private msgSrv: NzMessageService,
    private nzImageService: NzImageService,
    private cdr: ChangeDetectorRef,
    private settingService: SettingsService
  ) {
    this.company_id = this.settingService.user.company_id;
    //console.log(this.settingService.user.ID);
    if (this.settingService.user.ID == 1) {
      this.isAdmin = true;
    }
    this.loadCompanies();
    this.loadShops();
  }

  loadShops(companyID = 0): void {
    this.http.get(`api/shop_map`, { companyId: companyID }).subscribe(res => {
      this.shops = res.data['shops'];
      for (let i = 0; i < this.shops.length; i++) {
        // @ts-ignore
        this.shopMap[this.shops[i]['shop_id']] = this.shops[i]['fordeal_shop_name'];
      }
    });
  }

  ngOnInit(): void {
    this.loadDataFromServer(this.pi, this.ps, this.q);
  }

  loadDataFromServer(pageIndex: number, pageSize: number, s_params: any): void {
    this.loading = true;
    let params = new HttpParams().append('pi', `${pageIndex}`).append('ps', `${pageSize}`).appendAll(s_params);
    this.http.get(`${this.url}`, params).subscribe(res => {
      if (res.err_code != 0) {
        this.msgSrv.error(res.msg);
      }
      this.total = res.data.total;
      // 处理倒计时
      this.listOfData = res.data.list;
      if (this.listOfData) {
        for (let i = 0; i < this.listOfData.length; i++) {
          let joinReturnDate = new Date(this.listOfData[i]['joinReturnDate']);
          let expiredAt = joinReturnDate.setDate(joinReturnDate.getDate() + 5);
          let seconds = Math.floor(expiredAt - new Date().getTime()) / 1000;
          if (seconds > 0) {
            // @ts-ignore
            this.listOfData[i]['leftDay'] = Math.floor(seconds / 86400);
            // @ts-ignore
            this.listOfData[i]['leftTime'] = seconds - this.listOfData[i]['leftDay'] * 86400;
          } else {
            // @ts-ignore
            this.listOfData[i]['leftTime'] = 0;
          }
        }
      }
      this.loading = false;
    });
  }

  viewImg(refundId: number): void {
    this.http.get(`api/refund/${refundId}/img`).subscribe(res => {
      this.desc = [];
      let images: NzImage[] = [];
      for (let l in res.data['exceptionShootImgInfos']) {
        let imgInfos = res.data['exceptionShootImgInfos'][l];
        images.unshift({
          src: imgInfos['exceptionImgUrl']
        });
        let descItem: any[] = [];
        for (let m in imgInfos['exceptionShootTagList']) {
          descItem.push({
            bottom: imgInfos['exceptionShootTagList'][m]['height'],
            left: imgInfos['exceptionShootTagList'][m]['width'],
            content: imgInfos['exceptionShootTagList'][m]['tagContent']
          });
        }
        this.desc.push(descItem);
      }
      let nzImagePreview = this.nzImageService.preview(images, { nzZoom: 0.5, nzRotate: 0 });
      if (nzImagePreview.previewInstance.visible) {
        let idx = nzImagePreview.previewInstance.index;
        let insertHtml = ``;
        for (let descIndex in this.desc[idx]) {
          let style = `font-size: 18px; position: absolute; color: #ffffff;padding: 4px 4px 4px 20px;border-bottom: 2px solid;`;
          style += ` left: ${this.desc[idx][descIndex]['left']}%; top:  ${this.desc[idx][descIndex]['bottom']}%;`;
          insertHtml += `<p class="exception-img-desc" style="${style}">${this.desc[idx][descIndex]['content']}</p>`;
        }
        document.getElementsByClassName('ant-image-preview-img-wrapper')[0].insertAdjacentHTML('beforeend', insertHtml);
        setTimeout(() => {
          // todo 添加判断
          document.getElementsByClassName('ant-image-preview-switch-left')[0].addEventListener('click', (el: any) => {
            let rmEle = document.getElementsByClassName('exception-img-desc');
            for (let i = 0; i < rmEle.length; i++) {
              rmEle[i].remove();
            }
            insertHtml = ``;
            let nIdx = nzImagePreview.previewInstance.index;
            for (let descIndex in this.desc[nIdx]) {
              let style = `font-size: 18px; color: #ffffff;padding: 4px 4px 4px 20px;border-bottom: 2px solid; position: absolute;`;
              style += ` left: ${this.desc[nIdx][descIndex]['left']}%; top:  ${this.desc[nIdx][descIndex]['bottom']}%;`;
              insertHtml += `<p class="exception-img-desc" style="${style}">${this.desc[nIdx][descIndex]['content']}</p>`;
            }
            document.getElementsByClassName('ant-image-preview-img-wrapper')[0].insertAdjacentHTML('beforeend', insertHtml);
          });
          document.getElementsByClassName('ant-image-preview-switch-right')[0].addEventListener('click', (el: any) => {
            let rmEle = document.getElementsByClassName('exception-img-desc');
            for (let i = 0; i < rmEle.length; i++) {
              rmEle[i].remove();
            }
            let nIdx = nzImagePreview.previewInstance.index;
            insertHtml = ``;
            for (let descIndex in this.desc[nIdx]) {
              let style = `font-size: 18px; color: #ffffff;padding: 4px 4px 4px 20px;border-bottom: 2px solid; position: absolute;`;
              style += `left: ${this.desc[nIdx][descIndex]['left']}%; top: ${this.desc[nIdx][descIndex]['bottom']}%;`;
              insertHtml += `<p class="exception-img-desc" style="${style}">${this.desc[nIdx][descIndex]['content']}</p>`;
            }
            document.getElementsByClassName('ant-image-preview-img-wrapper')[0].insertAdjacentHTML('beforeend', insertHtml);
          });
        }, 100);
      }
    });
  }

  search() {
    this.pi = 1;
    this.ps = 30;
    this.loadDataFromServer(this.pi, this.ps, this.q);
  }

  pageIndexChange(pageIndex: number) {
    this.loadDataFromServer(pageIndex, this.ps, this.q);
  }

  pageSizeChange(pageSize: number) {
    this.loadDataFromServer(this.pi, pageSize, this.q);
  }

  reset(e: any) {
    e.preventDefault();
    this.pi = 1;
    this.ps = 30;
    this.q.skuType = 'skuId';
    this.q.skuTypeValue = '';
    this.q.shopId = 0;
    this.q.warehouseId = 0;
    this.q.externalOrderType = 0;
    this.loadDataFromServer(this.pi, this.ps, this.q);
  }

  //编辑进度（退货进度）
  refund_process(shopId: number, externalOrderId: string, trackingNumber: string, ssuId: string): void {
    console.log(shopId, externalOrderId, trackingNumber, ssuId);
    //return;
    let options: ModalHelperOptions = {
      size: 'lg'
    };
    this.modal
      .createStatic(
        BusinessRefundProcessComponent,
        {
          i: { shopId: shopId, externalOrderId: externalOrderId, trackingNumber: trackingNumber, ssuId: ssuId, pcdr: this.cdr, pobj: this }
        },
        options
      )
      .subscribe(() => {});
  }

  correctDatetime(value: any) {
    if (value) {
      value = value.replace('T', ' ').replace('Z', '');
      var timezoneOffset = new Date().getTimezoneOffset(); // 获取当前时区, 返回当前时区与UTC相差的分钟数
      var correct_ts = new Date(value).getTime() - timezoneOffset * 60 * 1000;
      var date = new Date(correct_ts);
      let Y = date.getFullYear(),
        M = date.getMonth() + 1 < 10 ? `0${date.getMonth() + 1}` : date.getMonth() + 1,
        D = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate(),
        h = date.getHours() < 10 ? `0${date.getHours()}` : date.getHours(),
        m = date.getMinutes() < 10 ? `0${date.getMinutes()}` : date.getMinutes(),
        s = date.getSeconds() < 10 ? `0${date.getSeconds()}` : date.getSeconds();
      value = `${Y}-${M}-${D} ${h}:${m}:${s}`;
    }
    return value;
  }

  companyList = [];
  loadCompanies(): void {
    this.http.get(`api/company_map`).subscribe(res => {
      this.companyList = res.data;
      if (this.companyList.length > 1) {
        this.isShow = true;
      }
    });
  }
  companyChange(companyID: number) {
    this.loadShops(companyID);
    this.cdr.detectChanges();
  }
}
